/*************************************
 * Created by WebStorm
 * Author : 艾尼亚尔·毛拉吾提
 * QQ : 524155792  WeChat : ainiyar0124
 * Created Time :2024/2/6 13:32
 Desc :
 **************************************/

import {ComputedRef, Ref, ref, unref, computed, toRaw, watch, h} from 'vue';
import {BasicTableProps} from '../types/Table.ts'
import {ColumnKey, TableBaseColumn} from 'naive-ui/lib/data-table/src/interface';
import {cloneDeep, isEqual} from 'lodash-es';
import {isArray, isString} from "@/util/is.ts";


export function useColumns(props: ComputedRef<BasicTableProps>, {getPaginationInfo}) {
    // @ts-ignore
    const {columns} =props;
    const columnsRef = ref(columns) as unknown as Ref<TableBaseColumn[]>;
    let cacheColumns:TableBaseColumn[] = toRaw(columns);
    const getColumnsRef = computed(() => {
        const columns = cloneDeep(unref(columnsRef));
        //添加操作列
        handleActionColumn(props, columns);
        //添加复选框列
        handleSelectionColumn(props, columns);
        //添加序列号列
        handleSerialNumber(props, columns)
        if (!columns) return [];
        return columns;
    })
    //数据表表头添加操作列
    const handleActionColumn = (props: ComputedRef<BasicTableProps>, columns: TableBaseColumn[]) => {
        const {actionColumn} = unref(props);
        if (!actionColumn) return;
        !columns.find((col) => col.key === 'action') && columns.push({...(actionColumn as any)});
    }
    //复选框列
    const handleSelectionColumn = (props: ComputedRef<BasicTableProps>, columns: TableBaseColumn[]) => {
        const {defaultSelection} = unref(props);
        const hasSelection = columns.find((col) => col.type === 'selection');
        if (hasSelection == undefined && defaultSelection) {
            const Selection: any = {type: 'selection', fixed: 'left',maxWidth: 50,disabled (row: any) {
                    return !!row.is_disabled
                }};
            columns.splice(0, 0, Selection);
        }
        return columns;
    }
    //数据序列号
    const handleSerialNumber = (props: ComputedRef<BasicTableProps>, columns: TableBaseColumn[]) => {
        const {defaultSerialNumber, serialNumberTitle} = unref(props);
        const hasSelection = columns.find((col) => col.type === 'selection');
        const {page, pageSize} = unref(getPaginationInfo);
        const SerialNumber: any = {
            title: serialNumberTitle, key: 'no', fixed: 'left', align: 'center', width: 80, resizable: true, render(_:any, rowIndex: number) {
                const index = page === 1 ? rowIndex + 1 : pageSize * (page - 1) + (rowIndex + 1);
                return h('span', null, {default: () => index});
            }
        }
        if (hasSelection && defaultSerialNumber) {
            columns.splice(1, 0, SerialNumber);
        } else if (hasSelection == undefined && defaultSerialNumber) {
            columns.splice(0, 0, SerialNumber);
        }
        return columns;
    }
    const setColumns = (columnList: string[]|TableBaseColumn[]) => {
        const columns: any[] = cloneDeep(columnList);
        if (!isArray(columns)) return;
        if (!columns.length) {
            columnsRef.value = [];
            return;
        }
        const cacheKeys:ColumnKey[] = cacheColumns.map((item:TableBaseColumn) => item.key);
        //针对拖拽排序
        if (!isString(columns[0])) {
            columnsRef.value = columns;
        } else {
            const newColumns: TableBaseColumn[] = [];
            cacheColumns.forEach((item:TableBaseColumn) => {
                if (columnList.includes(<any>item.key)) {
                    newColumns.push(item);
                }
            });
            if (!isEqual(cacheKeys, columns)) {
                newColumns.sort((prev, next) => {
                    return cacheKeys.indexOf(prev.key) - cacheKeys.indexOf(next.key);
                });
            }
            columnsRef.value = newColumns;
        }
    }
    const getColumns = () => {
        const columns = toRaw(unref(getColumnsRef));
        return columns.map((item) => {
            return {
                ...item,
                title: item.title,
                key: item.key,
                fixed: item.fixed || undefined,
            };
        });
    }
    const getCacheColumns = (isKey?: boolean) => {
        let keys: ColumnKey[] = cacheColumns.map((item: any) => item.key);
        return isKey ? keys : cacheColumns;
    }
    const setCacheColumnsField = (key: string | undefined, value: Partial<TableBaseColumn>) => {
        if (!key || !value) {
            return;
        }
        cacheColumns.forEach((item:TableBaseColumn) => {
            if (item.key === key) {
                Object.assign(item, value);
                return;
            }
        });
    }
    const getTableColumns = computed(() => {
        const pageColumns = unref(getColumnsRef);
        pageColumns.map((column) => {
            //默认 ellipsis 为true
            if (column.key !== 'action') {
                column.ellipsis = typeof column.ellipsis === 'undefined' ? {tooltip: true} : column.ellipsis;
            }
            return column;
        })
        return pageColumns;
    })
    watch(
        () => unref(props).columns,
        (columns: any) => {
            columnsRef.value = columns;
        }
    );
    return {
        setColumns,
        getColumns,
        getTableColumns,
        getCacheColumns,
        setCacheColumnsField,
    }
}